<?php

class Admin_AuthenticationController extends Zend_Controller_Action
{

    public function init()
    {
    	$this->_auth = Zend_Auth::getInstance();
    }

    public function indexAction()
    {
        if($this->_auth->hasIdentity()) {
        	$this->_redirect($this->view->adminURL('index'));
        }else {
        	$this->_redirect($this->view->adminURL('authentication', 'login'));
        }
    }

    public function loginAction()
    {
    	if($this->_auth->hasIdentity()) {
        	$this->_redirect($this->view->adminURL('index', 'index'));
        }
    	$authenticated = null;
    	$form = new Admin_Form_Login();
   	
		$form->setAction($this->view->url(array(
     		'module' => 'admin',
     		'controller' => 'authentication',
     		'action' => 'login'
 		)));

		$username = $this->getRequest()->getParam('username', '');
		$password = $this->getRequest()->getParam('password', '');
		if ($username && $password) {
			$authAdapter = $this->getAuthAdapter();
			
			$authAdapter->setIdentity($username);
			$authAdapter->setCredential(md5($password));
			$authenticated = $authAdapter->authenticate();
			if ($authenticated->isValid()) {
				//Login success
				$data = $authAdapter->getResultRowObject(null, 'password');
				$this->_auth->getStorage()->write($data);
				$this->_redirect($this->view->adminURL('index', 'index'));
			}else{
				$form->username->setValue($username);
			}
		}
		$this->view->headTitle('Login to Amin CP');
    	$this->view->form = $form;
    	$this->_helper->layout()->setLayout('layout_login');
        
    }
    
    public function logoutAction()
    {
        $this->_auth->clearIdentity();
       	$this->_redirect($this->view->adminURL('authentication', 'login'));
    }

	public function getAuthAdapter() {
		$authAdapter = new Zend_Auth_Adapter_DbTable (Zend_Db_Table::getDefaultAdapter() );
        
        $authAdapter
        	->setTableName('users')
        	->setIdentityColumn('username')
        	->setCredentialColumn('password');
		return $authAdapter;
	}
}































